﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using ShakeIt_.ServiceReference2;

namespace ShakeIt_
{
    public partial class registerPage : PhoneApplicationPage
    {
        private string _username;
        private string _password;
        private System.Windows.Threading.DispatcherTimer timer;

        public registerPage()
        {
            InitializeComponent();
        }

        private void commit_button_Click(object sender, RoutedEventArgs e)
        {
            string username = usernameBox.Text;
            string password = passwordBox.Password;
            string password2 = password_againBox.Password;
            string cellPhone = cellPhoneBox.Text;
            if (password != password2)
            {
                ErrorMessageBox.Text = "两次密码输入不一致";
            }
            else
            {
                _username = username;
                _password = password;
                Data.proxy.InsertUserCompleted += new EventHandler<InsertUserCompletedEventArgs>(proxy_InsertUserCompleted);
                Data.proxy.InsertUserAsync(username, password, cellPhone);
            }
        }

        void proxy_InsertUserCompleted(object sender, InsertUserCompletedEventArgs e)
        {
            ErrorMessageBox.Text = e.Result;
            if (e.Result == "注册成功")
            {
                ErrorMessageBox.Text += " 三秒后自动登录";
                timer = new System.Windows.Threading.DispatcherTimer();
                timer.Interval = new TimeSpan(0, 0, 3);
                timer.Tick += new EventHandler(loginAfterSuccessfullRegister);
                timer.Start();
            }
        }

        private void loginAfterSuccessfullRegister(object sender, EventArgs e)
        {
            Data.username = _username;
            string password = _password;
            Data.proxy.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(proxy_LoginCompleted);
            Data.proxy.LoginAsync(Data.username, password);
            timer.Stop();
        }

        void proxy_LoginCompleted(object sender, LoginCompletedEventArgs e)
        {
            Data.userId = e.Result;
            if (this.NavigationService.CanGoBack)
            {
                this.NavigationService.GoBack();
            }
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }
    }
}